import { defineStore } from 'pinia';

import { logout } from '@/api/modules/user';
import { LocalStorageService } from '@/utils/storage';

type State = {
  userInfo: TypeObject,
  menus: TypeObject[],
  authKeys: string[]
}
export const useUserStore = defineStore('_user', {
  state: (): State => ({
    userInfo: {},
    menus: [],
    authKeys: [],
  }),
  actions: {
    getUserInfo(): Promise<TypeObject> {
      return new Promise((resolve) => {
        // TODO: 调用后端接口获取用户基本信息和权限信息
        const userInfo = {
          authorization: 'TGT-820659-ik8G-Cexfz5NnqAicN-uYh5NuPmjNKRGlu6R6l6B0hha5jV9u9E39wH5X7vrogVuB8M-longhu',
          loginName: 'dony',
          loginTime: 1746978336887,
          userId: '39e9a23d-2a85-4f36-a4ac-cd6118566fa7',
          userName: 'dony',
          realName: '明豪'
        };

        const functions = [
          {
            code: 'FM_HOME',
            id: "46fd4232-e210-480c-b3f4-863f79206345",
            name: "首页",
          }
        ];

        // 获取所有的authKeys，包括组件下面配置的操作
        const authKeys = functions.map((func: TypeObject) => (func.code));
        this.setAuthKeys(authKeys);
        this.setMenus(functions); // am中配置的菜单和组件
        this.setUserInfo(userInfo); // 设置用户信息

        resolve({
          menus: functions,
          authKeys,
        });
      });
    },
    logout(): Promise<TypeObject> {
      return new Promise((resolve, reject) => {
        logout().then(({ data }: TypeObject) => {
          LocalStorageService.clear();
          resolve(data);
        }).catch(() => {
          reject(new Error('退出登录失败'));
        });
      });
    },
    setUserInfo(info: TypeObject) {
      this.userInfo = info;
      LocalStorageService.set('_user_info', info);
    },
    setMenus(data: TypeObject[]) {
      this.menus = data;
    },
    setAuthKeys(data: string[]) {
      this.authKeys = data;
    },
  },
});
